package com.example.springboot_mvc_demo.Interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:
 * <P> Date: 2024/7/16:15:04
 */

@SuppressWarnings({"unchecked", ""})
public class TimeInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TimeInterceptor.class);

    ThreadLocal<Long> time = new ThreadLocal<Long> ();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        long start = System.currentTimeMillis();
        time.set(start);
        //log.info("进入前置拦截器:user-agent:{}", agent);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long end = System.currentTimeMillis();
        log.info("接口总时常：{}", end -  time.get());

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        time.remove();
    }
}
